package com.jiaai.web.zfp.callback;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jiaai.pay.IPayAPI;
import com.jiaai.pay.entitiy.VPay;
import comm.utils.pay.comm.util.WeiXinUtil;
import comm.utils.pay.comm.util.XmlUtils;
import comm.utils.pay.weixin.entity.WXResEntity;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.TreeMap;

/**
 * class_name:WeiXinCallBackController
 * describe:------------------>微信支付异步通知
 * create_user:张昉平
 * create_date:2018/1/29
 * create_time:12:27
 */
@RestController
@RequestMapping("/api/v1/weixin")
public class WeiXinCallBackController {

    private static final Logger xlog = LoggerFactory.getLogger(WeiXinCallBackController.class);

    @Reference
    private IPayAPI payAPI;

    /**
     * 支付回调
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/appPayNotify")
    public String appPayNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BufferedReader reader = request.getReader();
        String line = "";
        StringBuffer inputString = new StringBuffer();
        try {
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            reader.close();
            String xmlStr = inputString.toString();
            xlog.error("----接收到的报文---".concat(xmlStr));
            Document document = DocumentHelper.parseText(xmlStr);
            TreeMap<String, Object> map = new TreeMap(XmlUtils.Dom2Map(document));

            String orderNo = map.get("out_trade_no").toString();
            VPay order = payAPI.getOneOrder(orderNo);

            if (order == null) {//没有该订单
                return returnWx("order no exist!");
            }
            if (order.getSettlementCode() == 1) {//已经结算了
                return returnWx();
            }
            if (order.getPrice().compareTo(new BigDecimal(map.get("total_fee").toString()).divide(new BigDecimal(100))) != 0) {//数额不对
                return returnWx("fee not correct!");
            }
            if (!order.getVerifyId().equals(map.get("appid").toString())) {//appid不对
                return returnWx("appid not correct!");
            }

            String oldSign = map.remove("sign").toString();
            String beforeSign = WeiXinUtil.getSignBefore(map, order.getVerifySecret());
            String sign = WeiXinUtil.MD5(beforeSign);
            //一定要校验签名
            boolean isCorrectSign = oldSign.equals(sign);

            WXResEntity res = WeiXinUtil.getWxResEntity(xmlStr);

            if (isCorrectSign) {
                boolean flag = payAPI.checkWXCallback(orderNo, res);
                if (flag) {
                    return returnWx();
                }
            }else {
                return returnWx("sign incorrect!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnWx("server error");
    }

    private String returnWx(){
        return "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>";
    }
    private String returnWx(String msg){
        return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA["+msg+"!]]></return_msg></xml>";
    }

}
